package com.leyou.trade.service.impl;

import com.leyou.common.exception.LyException;
import com.leyou.trade.entity.Order;
import com.leyou.trade.service.OrderService;
import com.leyou.trade.service.PayService;
import com.leyou.trade.utils.PayHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Map;

public class PayServiceImpl implements PayService {

    @Autowired
    private PayHelper payHelper;

    @Autowired
    private OrderService orderService;

    @Override
    public String createPayUrl(Long orderId) {
        Order order = this.orderService.getById(orderId);
        String payUrl = payHelper.getPayUrl(orderId, 1L, "乐游商城");
        return payUrl;
    }

    @Override
    public void handlerNotify(Map<String, String> notifyParam) {
        payHelper.checkResultCode(notifyParam);

        payHelper.checkReturnCode(notifyParam);

        payHelper.checkResponseSignature(notifyParam);

        String out_trade_no = notifyParam.get("out_trade_no");
        String total_fee = notifyParam.get("total_fee");

        if (StringUtils.isEmpty(out_trade_no) || StringUtils.isEmpty(total_fee)) {
            throw new LyException(400, "支付有误已报警");
        }

        Long orderId = Long.valueOf(out_trade_no);

        Order order = this.orderService.getById(orderId);

        //状态表达为未付款
        if (order.getStatus() == 1) {

            if (Long.valueOf(total_fee).longValue() != 1/*order.getActualFee().longValue()*/) {
                throw new LyException(400, "支付有误已报警");
            }
            //update tb_order set status = 2,pay_time = now() where order_id = #{orderId} and status = #{status}
            this.orderService.update()
                    .set("status",2)
                    .set("pay_time",new Date())
                    .eq("order_id",orderId)
                    .eq("status",1)
                    .update();
        }
    }
}
